package com.example.administrator.basedemos.okhttp;

import android.support.annotation.Nullable;

import com.example.administrator.basedemos.inter.ProgressListener;
import com.example.administrator.basedemos.utils.LogUtil;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * 创建者     ZCL
 * 创建时间   2018/3/14 14:14
 * 描述	      ${網絡攔截器}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */

public class ProgressResponse extends ResponseBody {
    private static final String TAG = "ProgressResponse";
    private ProgressListener mProgressListener;
    private ResponseBody     mResponseBody;
    private BufferedSource   mBufferedSource;

    public ProgressResponse(ResponseBody responseBody, ProgressListener progressListener) {
        this.mResponseBody = responseBody;
        this.mProgressListener = progressListener;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return mResponseBody.contentType();
    }

    @Override
    public long contentLength() {
        return mResponseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        //從返回的response中得到Source對象
        mBufferedSource = Okio.buffer(geteSource(mResponseBody.source()));
        return mBufferedSource;
    }

    public Source geteSource(Source source) {
        //通過Okio.buffer獲得BufferSource
        return Okio.buffer(new ForwardingSource(source) {
            long toalSize = contentLength();
            long len = 0;
            long sum = 0;
            int progress = 0;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                //读取长度 相當於is.read()
                len = super.read(sink, byteCount);
                //防止为-1时候减掉原本大小
                sum += (len == -1 ? 0 : len);
                progress = (int) ((sum * 1.0f / toalSize)*100);

                LogUtil.util(TAG, "progressLddfdsfis---------:" + progress);
                if (len == -1) {
                    mProgressListener.ProgressDone(toalSize);
                } else {
                    mProgressListener.progressUpdata(progress);
                }
                //可以在中間操作   但是判斷最後依據len不能變化 如換成progress
                return len;
            }
        });
    }
}
